import {baseUrl} from '../../settings'
export const BASE_URL = baseUrl
import {useUserStore} from '@/store/user'

import {checkURL} from "@/utils";

const userStore = useUserStore()


const myRequest = (options: any) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: checkURL(options.url) ? options.url : (BASE_URL + options.url),
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                'Authorization': userStore.token,
                ...options.header
            },
            success: (res: any) => {
                //refreshToken过期 未登录  返回主页
                if (res.data.code && (res.data.code === 420 || res.data.code === 405)) {
                    uni.redirectTo({
                        url: '/pages/common/auth/login/login',
                        success: function () {
                            uni.showToast({
                                icon: 'error',
                                title: '请重新登录'
                            })
                        }
                    })
                    return
                }
                //token过期 refreshToken更新token
                if (res.data.code && res.data.code === 410) {
                    uni.showToast({
                        icon: 'loading',
                        title: '请稍后重试',
                        duration: 500
                    })
                    // api.auth.refreshToken({
                    // 	'refreshToken': userStore.refreshToken
                    // }).then((res: any) => {
                    // 	userStore.setToken(res.data.data.token)
                    // 	userStore.setRefreshToken(res.data.data.refreshToken)
                    // 	uni.hideLoading()
                    // })
                    return
                }
                if (res.data.code && res.data.code !== 0) {
                    uni.showToast({
                        icon: 'error',
                        title: res.data.msg
                    })
                }
                resolve(res)
            },
            fail: (err) => {
                uni.showToast({
                    icon: 'error',
                    title: '请求接口失败'
                })
                reject(err)
            }
        })
    })
}
export default {
    myRequest,
}